import { RedisClient } from 'redis'
const redis = require("redis");
import { Observable, Subscriber } from 'rxjs'

class RedisSubscriber {
    private host: string;
    private port: number;
    private channel: string;
    private client: RedisClient

    constructor(host: string, port: number, channel: string) {
        this.host = host
        this.port = port
        this.channel = channel

        this.client = redis.createClient(port, host)
    }

    subscribe(): Observable<string> {
        const self = this
        const producer = (subscriber: Subscriber<string>) => {
            self.client.subscribe(self.channel)

            self.client.on("message", (channel: string, message: string) => {
                const messageSentToClient = `received message from channel: ${channel}, message: ${message}`
                subscriber.next(messageSentToClient)
            })

            self.client.on("unsubscribe", (channe: string, count: number) => {
                subscriber.complete()
            })
        }

        return new Observable<string>(producer)
    }

    dispose() {
        this.client.unsubscribe()
        this.client.quit()
    }

    about(){
        return "https://www.npmjs.com/package/redis"
    }
}

export { RedisSubscriber }